from os.path import exists

from yaml import safe_load_all, safe_load


class File:
    def __init__(self, file_path: str):
        # 判断文件是否存在
        if not exists(file_path):
            raise FileNotFoundError

        self._file_path = file_path
        self._data = None


class YamlReader(File):
    def __init__(self, yml_path: str, multi: bool = False):
        """
        :param yml_path:
        :param multi: 控制是否以多节的方式读取文件
        """
        super(YamlReader, self).__init__(yml_path)
        self._multi = multi

    @property
    def data(self):
        """
        读取 yaml 文件数据
        :return:
        """
        # 如果 self._data 非空，则无需重复打开文件读取数据
        if not self._data:
            with open(self._file_path, "rb") as fp:
                if self._multi:
                    # 读取多级的 yaml 文件
                    self._data = list(safe_load_all(fp))
                else:
                    self._data = safe_load(fp)
        return self._data
